package com.baizhi.controller;

import com.baizhi.constants.RedisPrefix;
import com.baizhi.dto.PhoneDTO;
import com.baizhi.util.SMSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RefreshScope
@RestController
@RequestMapping("captchas")
public class SmsController {

    private static final Logger log = LoggerFactory.getLogger(SmsController.class);
    private final RedisTemplate redisTemplate;


    @Autowired
    public SmsController(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @PostMapping
    public void sendLoginMessage(@RequestBody PhoneDTO phone) {

        log.info("手机号为, {}", phone);
        /**
         * 优化思路：
         * 发送短信验证码的同时，存储到redis数据库中
         */
        try {
            //发送短信验证码
            String code = SmsController.getCode();
            SMSUtils.sendMsg(phone.getPhone(), code);
            //将验证码加入redis数据库中，并设置超时时间为10分钟
            //TODO:将下面注释打开【redis生存时间】
            //redisTemplate.opsForValue().set(RedisPrefix.MSG_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(RedisPrefix.MSG_PREFIX + phone.getPhone(), code, 1, TimeUnit.DAYS);
            log.info("手机验证码为 {}", code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成四位验证码
    public static String getCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 4; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }


}

